# PowerShell script to build HOMEBOX for multiple platforms
Write-Host "Building HOMEBOX for multiple platforms..." -ForegroundColor Green

# Ensure dist directory exists
if (!(Test-Path "dist")) {
    New-Item -ItemType Directory -Path "dist" | Out-Null
}

# Build frontend if not already built
if (!(Test-Path "frontend\.output\public")) {
    Write-Host "Building frontend..." -ForegroundColor Yellow
    Set-Location "frontend"
    & pnpm run build
    Set-Location ".."
}

# Copy frontend files
Write-Host "Copying frontend files..." -ForegroundColor Yellow
if (!(Test-Path "backend\app\api\static\public")) {
    New-Item -ItemType Directory -Path "backend\app\api\static\public" | Out-Null
}
Copy-Item -Path "frontend\.output\public\*" -Destination "backend\app\api\static\public" -Recurse -Force

# Generate API docs
Write-Host "Generating API documentation..." -ForegroundColor Yellow
Set-Location "backend"
& swag fmt --dir=./app/api
& swag init --dir=./app/api,./internal/core/services,./internal/data/repo --parseDependency --output ./app/api/static/docs

# Build settings
$env:CGO_ENABLED = "0"
$buildFlags = @{
    ldflags = "-s -w"
    tags = "osusergo netgo static_build"
}

# Build targets
$targets = @(
    @{ GOOS = "linux"; GOARCH = "amd64"; output = "homebox-linux-amd64" },
    @{ GOOS = "linux"; GOARCH = "arm64"; output = "homebox-linux-arm64" },
    @{ GOOS = "windows"; GOARCH = "amd64"; output = "homebox-windows-amd64.exe" },
    @{ GOOS = "windows"; GOARCH = "arm64"; output = "homebox-windows-arm64.exe" },
    @{ GOOS = "darwin"; GOARCH = "amd64"; output = "homebox-darwin-amd64" },
    @{ GOOS = "darwin"; GOARCH = "arm64"; output = "homebox-darwin-arm64" }
)

Write-Host "Building binaries..." -ForegroundColor Green

foreach ($target in $targets) {
    $env:GOOS = $target.GOOS
    $env:GOARCH = $target.GOARCH
    
    Write-Host "Building $($target.GOOS) $($target.GOARCH)..." -ForegroundColor Cyan
    
    $outputPath = "../dist/$($target.output)"
    $buildCommand = "go build -ldflags='-s -w' -tags='osusergo netgo static_build' -o '$outputPath' ./app/api"
    
    Invoke-Expression $buildCommand
    
    if ($LASTEXITCODE -eq 0) {
        Write-Host "✅ $($target.GOOS) $($target.GOARCH) build complete" -ForegroundColor Green
    } else {
        Write-Host "❌ $($target.GOOS) $($target.GOARCH) build failed" -ForegroundColor Red
    }
}

Set-Location ".."

Write-Host "`n🎉 Cross-platform build complete!" -ForegroundColor Green
Write-Host "Built binaries:" -ForegroundColor Yellow
Get-ChildItem "dist\*" | ForEach-Object { Write-Host "  $($_.Name) - $([math]::Round($_.Length/1MB, 2)) MB" }

Write-Host "`nTo compress with UPX (optional):" -ForegroundColor Yellow
Write-Host "upx --best --lzma dist\*"